package com.cly.utils;

import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.Function;


/**
 * 默认值设置器
 *
 * @author by 春风能解释
 * <p>
 * 2025/2/10
 */
public class DefaultValueSetter<T> {

    /**
     * Set方法
     */
    private final Map<String, BiConsumer<T, String>> defaultSetters = new ConcurrentHashMap<>();
    /**
     * Get方法
     */
    private final Map<String, Function<T, String>> defaultGetters = new ConcurrentHashMap<>();

    /**
     * 添加字段
     *
     * @param fieldName 字段名
     * @param setter    set方法
     * @param getter    get方法
     * @return this
     */
    public DefaultValueSetter<T> addField(String fieldName, BiConsumer<T, String> setter, Function<T, String> getter) {
        defaultSetters.put(fieldName, setter);
        defaultGetters.put(fieldName, getter);
        return this;
    }

    /**
     * 设置默认值
     *
     * @param obj          对象
     * @param defaultValue 默认值
     */
    public void setDefaultValuesIfEmpty(T obj, String defaultValue) {
        for (Map.Entry<String, BiConsumer<T, String>> entry : defaultSetters.entrySet()) {
            String fieldName = entry.getKey();
            BiConsumer<T, String> setter = entry.getValue();
            Function<T, String> getter = defaultGetters.get(fieldName);
            String fieldValue = getter.apply(obj);
            if (!StringUtils.hasText(fieldValue)) {
                setter.accept(obj, defaultValue);
            }
        }
    }
}
